<template>
  <div>
    <!-- 使用NavBar -->
    <NavBar :pageTitle="'登录'" />

    <cell-group class="login-form">
      <div v-if="loginMode === 'password'">
        <field
          v-model="username"
          label="用户名"
          placeholder="请输入用户名"
          required
          clearable
          class="form-field"
        />
        <field
          v-model="password"
          type="password"
          label="密码"
          placeholder="请输入密码"
          required
          clearable
          class="form-field"
        />
      </div>

      <div v-if="loginMode === 'captcha'">
        <field
          v-model="username"
          label="用户名"
          placeholder="请输入用户名"
          required
          clearable
          class="form-field"
        />
        <field
          v-model="captcha"
          label="验证码"
          placeholder="请输入验证码"
          required
          clearable
          right-icon="code-o"
          @click-right-icon="sendCaptcha"
          class="form-field"
        >
          <template #button>
            <Button
              size="small"
              round
              :disabled="isSending"
              @click="sendCaptcha"
            >{{ captchaButtonText }}</Button>
          </template>
        </field>
      </div>

      <div class="toggle-login-mode">
        <Button round block @click="toggleLoginMode">{{ toggleButtonText }}</Button>
      </div>

      <div class="submit-button">
        <Button round block type="primary" @click="handleSubmit" :disabled="!canSubmit">登录</Button>
      </div>

      <div class="agreement">
        <checkbox v-model="agree" @change="onAgreeChange">我已阅读并同意相关协议</checkbox>
      </div>
    </cell-group>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import axios from 'axios'; // 引入 Axios
import { Field, Button, Checkbox, CellGroup } from 'vant';

// 导入NavBar
import NavBar from '../components/NavBar.vue';

// 引入 Vant 组件
import 'vant/es/field/style';
import 'vant/es/button/style';
import 'vant/es/checkbox/style';
import 'vant/es/cell-group/style';
import { rq } from '../utils/request';

// 导入 showToast
import { showToast } from 'vant';
import router from '@/router';

const username = ref('15244667237');
const password = ref('');
const captcha = ref('');
const loginMode = ref<'password' | 'captcha'>('password');
const isSending = ref(false);
const agree = ref(false);

// 计时器
let countdownTimer: any;

// 计时器剩余时间
const remainingTime = ref(3);

// 切换登录模式
function toggleLoginMode() {
  loginMode.value = loginMode.value === 'password' ? 'captcha' : 'password';
}

// 发送验证码
async function sendCaptcha() {
  if (isSending.value) return;

  isSending.value = true;

  try {
    const response = await rq('/code', 'get', { params: { username: username.value } });
    console.log('响应结果:', response.data.data.code);
    // 将response.data.data.code 的值回显到验证码输入框
    captcha.value = response.data.data.code;
  } catch (error) {
    console.error('请求失败:', error);
  }

  remainingTime.value = 3;
  countdownTimer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(countdownTimer);
      isSending.value = false;
      remainingTime.value = 3;
    }
  }, 1000);
}

// 计时器文本
const captchaButtonText = computed(() => {
  return isSending.value ? `${remainingTime.value}秒后重新发送` : '发送验证码';
});

// 切换按钮文本
const toggleButtonText = computed(() => {
  return loginMode.value === 'password' ? '切换到验证码登录' : '切换到密码登录';
});

// 表单提交
async function handleSubmit() {
  if (!agree.value) {
    alert('请先同意相关协议');
    return;
  }

  if (loginMode.value === 'password') {
    if (!username.value || !password.value) {
      alert('用户名和密码不能为空');
      return;
    }

    try {
      const response = await rq('/login/password', 'post', { username: username.value, password: password.value });
      showToast('密码登录成功');
      console.log('密码登录成功:', response);
    } catch (error) {
      console.error('密码登录失败:', error);
      showToast('密码登录失败，请检查用户名和密码');
    }
  } else if (loginMode.value === 'captcha') {
    if (!username.value || !captcha.value) {
      showToast('用户名和验证码不能为空');
      return;
    }

    try {
      const response = await rq('/login', 'post', { username: username.value, captcha: captcha.value });
      showToast('验证码登录成功');

      // 路由跳转到 /根目录
      router.push('/user');
    
      console.log('验证码登录成功:', response);
    } catch (error) {
      console.error('验证码登录失败:', error);
      showToast('验证码登录失败，请检查用户名和验证码');
    }
  }
}

// 协议勾选状态变化
function onAgreeChange(value: boolean) {
  agree.value = value;
}

// 是否可以提交
const canSubmit = computed(() => {
  if (loginMode.value === 'password') {
    return username.value && password.value && agree.value;
  } else if (loginMode.value === 'captcha') {
    return username.value && captcha.value && agree.value;
  }
  return false;
});
</script>

<style scoped>
body {
  color: #333; /* 文字颜色 */
}

.login-form {
  margin-top: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-field {
  margin-bottom: 10px;
}

.toggle-login-mode,
.submit-button,
.agreement {
  margin-top: 10px;
}

.agreement {
  text-align: center;
}

.button--primary {
  background-color: #FFA07A; /* 橙色按钮 */
  border-color: #FFA07A;
}

.button--primary:hover {
  background-color: #FF8C00; /* 深橙色按钮 */
  border-color: #FF8C00;
}

.checkbox__label {
  font-size: 14px;
}
</style>